<?php

    /**
     * @package      Updater
     * @subpackage   Updater
     *
     * @author       Thanh Tri PHAN
     */

    /*******************************************************************************
     *                                                                             *
     *                  Check environnement and load librairies                    *
     *                                                                             *
     ******************************************************************************/

     if (empty($_POST)) {
        die('Don\'t do that!');
     }

    set_time_limit(0);
    ini_set('max_execution_time', 0);

    // Require Main.php to load constants
    
    require_once '../../serum/app/Main.php';
    
    umask(0);
    Main::_initialize('admin');
    
    /*******************************************************************************
     *                                                                             *
     *                       Validate fields and connection                        *
     *                                                                             *
     ******************************************************************************/

    // Validate fields
    $currentType    = ucfirst($_POST['fieldType']);
    $updater        = Core_Updater::getInstance($currentType);
    
    if (!Core_Authentification::isConnected() || isset($_POST['fieldLogin']) || isset($_POST['fieldPwd'])) {
    	Core_Authentification::logoff();
	    $username = stripslashes($_POST['fieldLogin']);
	    $password = stripslashes($_POST['fieldPwd']);
	    
	    try {
	    	$result = Core_Authentification::login($username, $password);
	    } catch (Exception $e) {
            $failureReason = '<b>Identifiant et/ou mot de passe incorrect !</b><br /><br />' . htmlspecialchars($e->getMessage(), ENT_QUOTES);
            echo "{success: false, errors: { reason: '" . $failureReason . "' }}";
            die();
	    }

        if (!$result->isValid()) {
            $failureReason = '<b>Identifiant et/ou mot de passe incorrect !</b><br /><br />Vous n\\\'êtes pas autorisé à procéder à la mise à jour de Serum.';
            echo "{success: false, errors: { reason: '" . $failureReason . "' }}";
            die();
        } else if (!in_array($username, $updater->getAuthorizedAccounts())) {
	        $failureReason = '<b>Action non autorisée !</b><br /><br />Votre compte ne possède pas les autorisations nécessaires pour procéder à la mise à jour de Serum.';
	        echo "{success: false, errors: { reason: '" . $failureReason . "' }}";
	        die();
        }
    }
    
    $version = (int)$_POST['fieldVersion'];
    $versionValid = true;
    
    if ($_POST['fieldUpdate'] == 'version' && !is_int($version)) {
    	$versionValid = false;
    }
    if ($updater->getLatestVersion() < $version) {
        $versionValid = false;
    }
    
    if ($versionValid == false) {
        $failureReason = '<b>Numéro de version invalide !</b>';
        echo "{success: false, errors: { reason: '" . $failureReason . "' }}";
        die();
    }
    if (($_POST['fieldUpdate'] == 'latest' && $updater->getCurrentVersion() == $updater->getLatestVersion())
         || ($_POST['fieldUpdate'] == 'version' && $updater->getCurrentVersion() == $version) ) {
        $failureReason = '<b>Vous êtes déjà à la version '.$updater->getCurrentVersion().' !</b>';
        echo "{success: false, errors: { reason: '" . $failureReason . "' }}";
        die();
    }

    /*******************************************************************************
     *                                                                             *
     *                      Process update                                         *
     *                                                                             *
     ******************************************************************************/

    // Try to update
    try {        
        if ($_POST['fieldUpdate'] == 'latest')
           $updater->migrate();
        else
           $updater->migrate($version);

    } catch (Doctrine_Migration_Exception $e) {        
        $failureReason = '<b>La mise à jour de Serum a échouée !</b><br /><br />' . htmlspecialchars($e->getMessage(), ENT_QUOTES);
        echo "{success: false, errors: { reason: '" . $failureReason . "' }}";
        die();
    }
    
    $basePath = $_SERVER['REQUEST_URI'];
    $basePath = explode('/', $basePath);
    $basePath = array_slice($basePath, 0, -3);
    $basePath = implode('/', $basePath);
    $post['basePath'] = $basePath . '/';
    
    // Send redirection page value
    echo "{success: true, page: '" . $basePath . "/serum/index.php' }";
